package com.mz.mattress.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mz.mattress.admin.api.req.SaleListReq;
import com.mz.mattress.admin.api.req.SaleQueryReq;
import com.mz.mattress.admin.api.resp.IntegerCount;
import com.mz.mattress.admin.api.resp.SaleSum;
import com.mz.mattress.admin.mapper.*;
import com.mz.mattress.admin.service.SaleService;
import com.mz.mattress.api.common.Constants;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.entity.Device;
import com.mz.mattress.api.entity.MemberMer;
import com.mz.mattress.api.entity.Merchant;
import com.mz.mattress.api.entity.Sale;
import com.mz.mattress.api.enums.MerchantStatusEnum;
import com.mz.mattress.api.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class SaleServiceImpl implements SaleService {

    @Autowired
    private SaleMapper saleMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private MemberMerMapper memberMerMapper;

    @Autowired
    private OrderUseTimesBonusMapper orderUseTimesBonusMapper;

    @Override
    public Result<IPage<Sale>> listPage(SaleQueryReq req) {
        Page page = req.newPage();
        //查询一级服务商
        Page<Sale> list = saleMapper.listPage(page, req.getProvince(), req.getCity(), req.getDistrict(),
                req.getName(), req.getStatus(), null, req.getStartTime(), req.getEndTime());
        return Result.ok(list);
    }

    @Override
    public Result<Sale> getById(Integer id) {

        if (id == 0) {
            return Result.fail("服务商不存在");
        }

        Sale sale = saleMapper.selectById(id);
        if (sale == null) {
            return Result.fail("服务商不存在");
        }

        if (sale.getPid() == 0) {
            List<Sale> list = saleMapper.selectByPid(id);
            sale.setList(list);
        }

        SaleSum saleSum = getSaleSum(sale);
        sale.setMerchantSum(saleSum.getMerchantSum());
        sale.setBonusSum(saleSum.getBonusSum());

        return Result.ok(sale);
    }

    @Override
    public Result add(Sale sale) {

        if (StringUtils.isEmpty(sale.getMobile())) {
            return Result.fail("请输入手机号");
        }

        if (StringUtils.isEmpty(sale.getName())) {
            return Result.fail("请输入姓名");
        }

        String mobile = sale.getMobile();

        Sale one = saleMapper.selectByMobile(mobile);
        if (one != null) {
            return Result.fail("手机号已存在");
        }

        //绑定会员信息
        MemberMer memberMer = memberMerMapper.selectByMobile(mobile);
        if (memberMer != null) {
            sale.setMemberId(memberMer.getId());
        }

        Integer bonusRatio = sale.getBonusRatio();
        if (bonusRatio == null) {
            sale.setBonusRatio(Constants.DEFAULT_SALE_BONUS_RATIO);
        } else if (bonusRatio < 1 || bonusRatio > 100) {
            return Result.fail("佣金比例范围（1-100）");
        } else {
            sale.setBonusRatio(bonusRatio);
        }
        saleMapper.insert(sale);

        return Result.ok();
    }

    @Override
    public Result updateById(Sale sale) {

        // 手机号不能改
        sale.setMobile(null);
        sale.setMemberId(null);

        Integer bonusRatio = sale.getBonusRatio();
        if (bonusRatio == null) {
            sale.setBonusRatio(Constants.DEFAULT_SALE_BONUS_RATIO);
        } else if (bonusRatio < 1 || bonusRatio > 100) {
            return Result.fail("佣金比例范围（1-100）");
        } else {
            sale.setBonusRatio(bonusRatio);
        }

        saleMapper.updateById(sale);

        return Result.ok();
    }

    @Override
    public Result updateMobile(Integer id, String mobile) {

        return null;
    }

    @Override
    public Result deleteByIds(Set<Integer> ids) {
        saleMapper.deleteBatchIds(ids);
        return Result.ok();
    }

    @Override
    public Result<SaleSum> headSum(Integer id) {

        Sale sale = saleMapper.selectById(id);
        if (sale == null) {
            return Result.fail("服务商不存在");
        }

//        SaleSum saleSum = new SaleSum();
//        saleSum.setMerchantSum(sale.getMerchantSum());
//        saleSum.setMerchantApply(sale.getMerchantApply());
//        saleSum.setDeviceSum(sale.getDeviceSum());
//        saleSum.setDeviceOff(sale.getDeviceOff());
//        saleSum.setBonusSum(sale.getBonusSum());
//        saleSum.setBonusCurMonth(sale.getBonusCurMonth());

        SaleSum saleSum = getSaleSum(sale);

        return Result.ok(saleSum);
    }

    //实时统计
    @NotNull
    private SaleSum getSaleSum(Sale sale) {

        Integer id = sale.getId();

        SaleSum saleSum = new SaleSum();

        String columnName = sale.getPid() == 0 ? "top_sale_id" : "sale_id";
        List<IntegerCount> merchantCount = merchantMapper.selectSumByColumn(columnName, id);

        int pass = 0;
        int apply = 0;
        for (IntegerCount statusCount : merchantCount) {
            if (statusCount.getStatus() == MerchantStatusEnum.SUBMITTED.getValue()) {
                apply += statusCount.getCount();
            } else if (statusCount.getStatus() >= MerchantStatusEnum.CHECK_PASS.getValue()) {
                pass += statusCount.getCount();
            }
        }
        saleSum.setMerchantSum(pass);
        saleSum.setMerchantApply(apply);

        List<IntegerCount> deviceCount = deviceMapper.selectSumByColumn(columnName, id);

        int total = 0;
        int off = 0;
        for (IntegerCount statusCount : deviceCount) {
            //状态 1离线 2在线 3使用中 4已禁用
            if (statusCount.getStatus() == 1) {
                off = statusCount.getCount();
            }
            total += statusCount.getCount();
        }
        saleSum.setDeviceSum(total);
        saleSum.setDeviceOff(off);

        //类型 0平台 1商家 2销售 3子销售
        int type = 3;
        if (sale.getPid() == 0) {
            type = 2;
        }

        Integer totalBonus = orderUseTimesBonusMapper.selectSum(type, id, null, null);
        saleSum.setBonusSum(totalBonus == null ? 0 : totalBonus);

        Integer curMonthBonus = orderUseTimesBonusMapper.selectSum(type, id, null, DateUtil.getNowMonth());
        saleSum.setBonusCurMonth(curMonthBonus == null ? 0 : curMonthBonus);
        return saleSum;
    }

    @Override
    public Result<List<Sale>> searchByMobile(String mobile) {
        List<Sale> sales = saleMapper.searchByMobile(mobile);
        return Result.ok(sales);
    }

    @Override
    public Result<IPage<Merchant>> merchantPage(SaleListReq req) {

        if (req.getSaleId() == null && req.getPid() == null) {
            return Result.fail("参数错误");
        }

        Page<Merchant> list = merchantMapper.listPage(req.newPage(), null, null, null,
                null, null, req.getSaleId(), req.getPid(), null, req.getStatus(),
                req.getStatusType(), null, null, null, null);

        return Result.ok(list);
    }

    @Override
    public Result<IPage<Sale>> salePage(SaleListReq req) {
        //查询一级服务商
        Page<Sale> list = saleMapper.listPage(req.newPage(), null, null, null,
                null, req.getStatus(), req.getPid(), null, null);
        return Result.ok(list);
    }

    @Override
    public Result<IPage<Device>> devicePage(Integer id, Integer status, Integer pageNo, Integer pageSize) {
        return null;
    }

    @Override
    public void doSum() {

        List<Sale> list = saleMapper.list();

        for (Sale sale : list) {

            SaleSum saleSum = getSaleSum(sale);

            Sale update = new Sale();
            update.setId(sale.getId());
            update.setMerchantSum(saleSum.getMerchantSum());
            update.setDeviceSum(saleSum.getDeviceSum());
            update.setDeviceOff(saleSum.getDeviceOff());
            update.setMerchantApply(saleSum.getMerchantApply());
            update.setBonusSum(saleSum.getBonusSum());
            update.setBonusCurMonth(saleSum.getBonusCurMonth());
            saleMapper.updateById(update);

        }


    }


}
